# -*- coding: utf-8 -*-

'''
服务包函数
'''
from ...pao_python.pao.data import process_db, dataframe_to_list, DataProcess, DataList
import pandas as pd
import uuid
import datetime
import re
import hashlib
from ...pao_python.pao.service.security.security_service import RoleService
from ...pao_python.pao.service.security.security_utility import get_current_account_id
from ...service.common import insert_data, find_data, update_data, delete_data, get_condition, get_info, get_current_organization_id, execute_python
from ...service.buss_pub.bill_manage import BillManageService, OperationType, TypeId, Status
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.mongo_bill_service import MongoBillFilter
from ...service.app.service_detail import ServiceProductDetailService


class ServiceItemPackageService(MongoService):
    ''' 服务包 '''

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        DataProcess.__init__(self, db_addr, db_port, db_name, db_user, db_pwd)
        # self.db_name = db_name
        self.inital_password = inital_password
        self.session = session
        self.role_service = RoleService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)
        self.detail_service = ServiceProductDetailService(
            self.db_addr, self.db_port, self.db_name, self.db_user, self.db_pwd, self.inital_password, self.session)

    def get_service_item_package(self, order_ids, condition, page=None, count=None):
        '''查询服务包列表'''
        keys = ['id', 'name', 'organization_name', 'is_external']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.match_bill(C('organization_id').inner(order_ids))\
            .lookup_bill('PT_User', 'organization_id', 'id', 'user')\
            .add_fields({
                'organizational_name': '$user.name',
                'create_date': self.ao.date_to_string('$create_date'),
                'modify_date': self.ao.date_to_string('$modify_date')})\
            .match_bill((C('id') == values['id']) & (C('is_external') == values['is_external']) & C('name').like(values['name']) & C('user.name').like(values['organization_name']))\
            .lookup_bill('PT_Service_Item', 'service_item_id', 'id', 'item')\
            .project({'_id': 0, 'user._id': 0, 'item._id': 0, 'option._id': 0})\

        res = self.page_query(_filter, 'PT_Service_Product', page, count)
        # if res['result']:
        #     for result in res['result']:
        #         scope_list = []
        #         for scope_id in result['application_scope']:
        #             _filter_scope=  MongoBillFilter()
        #             _filter_scope.match_bill((C('id') == scope_id)).project({'_id': 0})
        #             res_scope = self.query(_filter_scope,'PT_Service_Scope')
        #             if res_scope:
        #                 scope_list.append(res_scope[0].get('name'))
        #         result['scope_name'] = '-'.join(scope_list)
        # 循环查询服务选项表
        # if 'id' in list(condition.keys()):
        #     if res['result'][0].get('service_item'):
        #         _filter_item = MongoBillFilter()
        #         _filter_item.match_bill(C('id') == res['result'][0].get('service_item_id')).project({'_.id':0})
        #         res_item = self.query(_filter_item,'PT_Service_Item')
        #         if res_item:
        #             res['result'][0]['service_item'][servicr_index]['item_type_id'] = res_item[0].get('item_type')
        #         if res['result'][0].get('service_item')[servicr_index].get('service_options'):
        #             for option_index in range(len(res['result'][0].get('service_item')[servicr_index].get('service_options'))):

        #                 _filter2 = MongoBillFilter()
        #                 _filter2.match_bill((C('id') == res['result'][0]['service_item']
        #                                 [servicr_index]['service_options'][option_index]['id']))
        #                 res2 = self.page_query(
        #                     _filter2, "PT_Service_Option", 1, 1)
        #                 if res2['result']:
        #                     res['result'][0]['service_item'][servicr_index]['service_options'][
        #                         option_index]['option_content'] = res2['result'][0].get('option_content')
        #                     res['result'][0]['service_item'][servicr_index]['service_options'][
        #                         option_index]['name'] = res2['result'][0].get('name')
        # keys = ['id', 'name','organization_name']
        # values = self.get_value(condition, keys)
        # _filter = MongoBillFilter()
        # _filter.lookup_bill('PT_User', 'org_id', 'id', 'user')\
        #     .add_fields({
        #         'organizational_name': '$user.name',
        #         'create_date': self.ao.date_to_string('$create_date'),
        #         'modify_date': self.ao.date_to_string('$modify_date')})\
        #     .match_bill((C('id') == values['id']) & C('name').like(values['name']) & C('$user.name').like(values['organization_name']))\
        #     .project({'_id': 0,'user._id': 0})
        # res = self.page_query(_filter, "PT_Service_Product", page, count)
        # if res['result']:
        #     for result in res['result']:
        #         scope_list = []
        #         for scope_id in result['application_scope']:
        #             _filter_scope=  MongoBillFilter()
        #             _filter_scope.match_bill((C('id') == scope_id)).project({'_id': 0})
        #             res_scope = self.query(_filter_scope,'PT_Service_Scope')
        #             if res_scope:
        #                 scope_list.append(res_scope[0].get('name'))
        #         result['scope_name'] = '-'.join(scope_list)
        #     # 循环查询服务选项表
        #     if 'id' in list(condition.keys()):
        #         if res['result'][0].get('service_item'):
        #             for servicr_index in range(len(res['result'][0].get('service_item'))):
        #                 _filter_item = MongoBillFilter()
        #                 _filter_item.match_bill(C('id') == res['result'][0].get('service_item')[servicr_index].get('service_item')).project({'_.id':0})
        #                 res_item = self.query(_filter_item,'PT_Service_Item')
        #                 if res_item:
        #                     res['result'][0]['service_item'][servicr_index]['item_type_id'] = res_item[0].get('item_type')
        #                 if res['result'][0].get('service_item')[servicr_index].get('service_options'):
        #                     for option_index in range(len(res['result'][0].get('service_item')[servicr_index].get('service_options'))):

        #                         _filter2 = MongoBillFilter()
        #                         _filter2.match_bill((C('id') == res['result'][0]['service_item']
        #                                         [servicr_index]['service_options'][option_index]['id']))
        #                         res2 = self.page_query(
        #                             _filter2, "PT_Service_Option", 1, 1)
        #                         if res2['result']:
        #                             res['result'][0]['service_item'][servicr_index]['service_options'][
        #                                 option_index]['option_content'] = res2['result'][0].get('option_content')
        #                             res['result'][0]['service_item'][servicr_index]['service_options'][
        #                                 option_index]['name'] = res2['result'][0].get('name')

        return res

    def update_service_item_package(self, service_item_package):
        ''' 新增/修改服务包'''
        res = 'Fail'

        # 解决没有组织机构id的问题
        if 'organization_id' not in service_item_package or ('organization_id' in service_item_package and service_item_package['organization_id'] == ''):
            service_item_package['organization_id'] = get_current_organization_id(
                self.session)
        # 在新增或者编辑产品时候保存该产品/套餐当前的金额
        price = 0
        if service_item_package['is_service_item'] == 'true':
            # 单个产品，带入公式
            if 'valuation_formula' in service_item_package and 'service_option' in service_item_package:
                if len(service_item_package['valuation_formula']) > 0 and 'formula' in service_item_package['valuation_formula'][0]:
                    price = execute_python(service_item_package.get('valuation_formula')[0].get(
                        'formula'), service_item_package.get('service_option'), 'name', 'option_value')
        else:
            # 产品套餐
            if 'service_product' in service_item_package and len(service_item_package['service_product']) > 0:
                for item in service_item_package['service_product']:
                    pruduct_detail = self.detail_service.get_service_product_package_detail(
                        {'id': item.get('product_id')})
                    if len(pruduct_detail) > 0 and 'total_price' in pruduct_detail[0]:
                        product_item_price = pruduct_detail[0].get(
                            'total_price')
                    price += float(product_item_price) * \
                        int(service_item_package['remaining_times'])
        service_item_package['service_package_price'] = price

        def process_func(db):
            nonlocal res
            if 'id' in service_item_package.keys():
                bill_id = self.bill_manage_service.add_bill(OperationType.update.value,
                                                            TypeId.serviceProduct.value, service_item_package, 'PT_Service_Product')
                if bill_id:
                    res = 'Success'
            else:
                bill_id = self.bill_manage_service.add_bill(OperationType.add.value,
                                                            TypeId.serviceProduct.value, service_item_package, 'PT_Service_Product')
                if bill_id:
                    res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def delete_service_item_package(self, service_item_package_ids):
        '''删除服务包接口

        Arguments:
            service_item_package   {ids}      数据id
        '''
        res = 'fail'

        def process_func(db):
            nonlocal res
            ids = []
            if isinstance(service_item_package_ids, str):
                ids.append(service_item_package_ids)
            else:
                ids = service_item_package_ids
            for service_scope_id in ids:
                # 查询被删除的数据信息
                data = find_data(db, 'PT_Service_Product', {
                    'id': service_scope_id, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    self.bill_manage_service.add_bill(OperationType.delete.value,
                                                      TypeId.serviceProduct.value, data[0], 'PT_Service_Product')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res
